<template>
  <view class="check-in-container">
    <view class="content">
      <!-- 个人信息卡片 -->
      <view class="card">
        <view class="card-title">
          <view class="title-line"></view>
          <text>个人信息</text>
        </view>
        <view class="card-content">
          <u-form :model="formData" ref="uForm" :errorType="['message']" labelPosition="left" :labelWidth="140">
            <u-form-item label="姓名" prop="name" required borderBottom class="form-item">
              <u-input v-model="formData.name" placeholder="请输入姓名" border />
            </u-form-item>
            <u-form-item label="手机号" prop="contacts" required borderBottom class="form-item">
              <u-input v-model="formData.contacts" placeholder="请输入手机号" type="number" maxlength="11" border />
            </u-form-item>
            <u-form-item label="身份证" prop="idCardNumber" required borderBottom class="form-item">
              <u-input v-model="formData.idCardNumber" placeholder="请输入身份证号码" border />
            </u-form-item>
          </u-form>
        </view>
      </view>
      
      <!-- 房租信息卡片 -->
      <view class="card">
        <view class="card-title">
          <view class="title-line"></view>
          <text>房租信息</text>
        </view>
        <view class="card-content">
          <u-form :model="formData" ref="rentForm" :labelWidth="140" labelPosition="left">
            <u-form-item label="开始时间" required class="form-item">
              <text class="readonly-text">{{ formatDate(formData.checkInStart) || '暂无数据' }}</text>
            </u-form-item>
            <u-form-item label="结束时间" required class="form-item">
              <text class="readonly-text">{{ formatDate(formData.checkInEnd) || '暂无数据' }}</text>
            </u-form-item>
            <u-form-item label="租金类型" required class="form-item">
              <text class="readonly-text">{{ getRentCollectCycleText(formData.rentCollectCycle) || '暂无数据' }}</text>
            </u-form-item>
            <u-form-item label="租金" required class="form-item">
              <text class="readonly-text">{{ formData.rent ? formData.rent + ' 元' : '暂无数据' }}</text>
            </u-form-item>
            <u-form-item label="押金" required class="form-item">
              <text class="readonly-text">{{ formData.deposit ? formData.deposit + ' 元' : '暂无数据' }}</text>
            </u-form-item>
            <u-form-item label="支付类型" required class="form-item">
              <text class="readonly-text">{{ getRentTypeText(formData.rentType) || '暂无数据' }}</text>
            </u-form-item>
          </u-form>
        </view>
      </view>
      
      <!-- 提交按钮 -->
      <view class="submit-container">
        <u-button type="primary" @click="submitCheckIn" :loading="submitting">提交入住申请</u-button>
      </view>
    </view>
    
    <!-- 提示框 -->
    <u-toast ref="uToast" />
    <u-modal 
      v-model="showConfirmModal" 
      title="确认提交" 
      content="确定要提交入住申请吗？" 
      showCancelButton 
      @confirm="confirmSubmit"
    ></u-modal>
  </view>
</template>

<script>
import { greet, checkBindWechat, bindWechat } from '@/api/login'
export default {
  data() {
    return {
      formData: {
        name: '',
        contacts: '',
        idCardNumber: '',
        checkInStart: '',
        checkInEnd: '',
        rent: '',
        deposit: '',
        rentType: '',
        rentCollectCycle: '',
        roomId: '',
        openId: ''
      },
      submitting: false,
      showConfirmModal: false,
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        contacts: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ],
        idCardNumber: [
          { required: true, message: '请输入身份证号码', trigger: 'blur' },
          { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证号码格式不正确', trigger: 'blur' }
        ]
      }
    };
  },
  onLoad(options) {
    console.log("数据options", options);
    
    
    // 解析二维码携带的参数
    if (options) {
      let url = decodeURIComponent(options.q)
      // 提取参数
      let params = url.split('?')[1].split('&')
      let paramsObj = {}
      params.forEach(item => {
        let [key, value] = item.split('=')
        paramsObj[key] = value
      })
      console.log("数据url", paramsObj);
      const {
        roomId,
        checkInStart,
        checkInEnd,
        rent,
        deposit,
        rentType,
        rentCollectCycle
      } = paramsObj;
      
      this.formData = {
        ...this.formData,
        roomId,
        checkInStart,
        checkInEnd,
        rent,
        deposit,
        rentType,
        rentCollectCycle
      };
    }
  },
  methods: {
    formatDate(dateString) {
      console.log("数据", dateString);
      if (!dateString) return '';
      const date = new Date(dateString);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    },
    getRentCollectCycleText(value) {
      const map = {
        '1': '月租金',
        '2': '日租金'
      };
      return map[value] || '';
    },
    getRentTypeText(value) {
      const map = {
        '1': '每1月',
        '2': '每2月',
        '3': '每3月',
        '4': '每4月',
        '5': '每半年',
        '6': '每一年',
        '7': '一次性'
      };
      return map[value] || '';
    },
    submitCheckIn() {
      // 表单验证
      this.$refs.uForm.validate(valid => {
        if (valid) {
          this.showConfirmModal = true;
        }
      });
    },
    async confirmSubmit() {
      this.submitting = true;
      try {

        // 提交入住信息
        const result = await this.submitCheckInData();
        if (result) {
          this.$refs.uToast.show({
            title: '提交成功',
            type: 'success'
          });
          
          this.handleLogin()
        } else {
          this.$refs.uToast.show({
            title: '提交失败，请稍后重试',
            type: 'error'
          });
        }
      } catch (error) {
        console.error('提交入住申请失败:', error);
        this.$refs.uToast.show({
          title: '提交失败，请稍后重试',
          type: 'error'
        });
      } finally {
        this.submitting = false;
      }
    },
    // 微信登录
    async handleLogin() {
        uni.login({
          success: async (res) => {
            console.log("微信登录", res);
            if (res.code) {
              let greetRes = await greet(res.code)
              // 获取openid 绑定
              console.log(greetRes);
              let openid = greetRes.data.openid
              this.formData.openId = openid
              checkBindWechat(openid).then(async checkRes => {
                console.log("check:>>", checkRes);
                if (!checkRes.data) {
                  await bindWechat(openid)
                }
              })
              this.wechatLogin(openid);
            }
          }
        })
      },
      wechatLogin(openid) {
        this.$store.dispatch('WechatLogin', openid).then(() => {
        checkBindWechat(openid).then(async checkRes => {
          console.log("check:>>", checkRes);
          if (!checkRes.data) {
            await bindWechat(openid)
          }
        })
        this.loginSuccess()
        })
      },
      // 登录成功后，处理函数
      loginSuccess(result) {
        // 设置用户信息
        this.$store.dispatch('GetInfo').then(res => {
          this.$tab.reLaunch('/pages/index')
        })
      },
    async submitCheckInData() {
      try {
        const response = await this.$http.post('/api/tenant/checkIn', this.formData);
        return response.data && response.data.code === 200;
      } catch (error) {
        console.error('提交入住数据失败:', error);
        return false;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.check-in-container {
  min-height: 100vh;
  background-color: #f5f6fa;
  
  .content {
    padding: 15px;
  }
  
  .card {
    background-color: #fff;
    border-radius: 12px;
    margin-bottom: 15px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    overflow: hidden;
    
    .card-title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
      padding: 16px;
      border-bottom: 1px solid #eee;
      display: flex;
      align-items: center;
      
      .title-line {
        width: 4px;
        height: 18px;
        background-color: #3c9cff;
        border-radius: 2px;
        margin-right: 8px;
      }
    }
    
    .card-content {
      padding: 16px 24px;
      /deep/ .u-form {
        .u-form-item {
          padding: 8px 0;
          &:after {
            border-bottom-width: 0;
          }
        }
      }
    }
  }

  .form-item {
    // margin-bottom: 15px;
  }
  
  .readonly-text {
    color: #666;
    font-size: 14px;
    line-height: 40px;
    display: block;
    text-align: right;
  }
  
  .submit-container {
    padding: 20px 15px 30px;
  }
}
</style>
